package com.example.interceptors;

import com.example.handlers.BaseContext;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器生效了...");
        String token = request.getHeader("Authorization");
        if(token==null){
            log.info("token丢失...");
            return false;
        }
        token=token.replace("Bearer ","");
        if(!jwtUtil.validateToken(token)){
            log.info("token已过期...");
            return false;
        }

//        long tid = Thread.currentThread().getId();
//        System.out.println("拦截器 线程id"+tid);

        Claims claims = jwtUtil.parseToken(token);
        Integer id = claims.get("id", Integer.class);

        // 存入线程变量
        BaseContext.setCurrentId(id);

        return true;
    }
}
